import { MessageBox, Message } from "element-ui"

function SimpleDraw() {

  this.min = 50;
  this.scaleValue=1;
  this.LINE = null;
  this.CREATELINESUCCESS = false;
  this.START_DOT_KEY = null;
  this.CONTEXTMENU = null;
  this.INDARGAREA = false;
  this.RESIZECORE = null;
  this.resize = {};
  this.json = {
    'core': {},
    'line': {}
  };
  this.dragEles = {};

}
SimpleDraw.prototype.option = function (options = {}) {
  this.options = {
    edit: true,
    scale:false,
    effectAllowed: 'copy',
    line: {
      style: {
        stroke: "#58cbf7",
        strokeWidth: 2,
        strokeLinejoin: "round",
        fill: "none",
      }
    },
    core: {
      rect: {
        label: "",
        shape: "rect",
        coreStyle: {
          width: "80px",
          height: "60px",
          zIndex: "2"
        },
        labelStyle: {
          alignItems: "center",
          justifyContent: "center",
          textAlign:"center",
          fontSize: '12px'
        },
        style: {
          width: '100%',
          height: '100%',
          backgroundColor: '#f5f5f5',
          border:"1px solid #dedede"
        }
      },
      circle: {
        label: "",
        shape: "circle",
        coreStyle: {
          width: "80px",
          height: "80px",
          zIndex: "2"
        },
        labelStyle: {
          alignItems: "center",
          justifyContent: "center",
          textAlign:"center",
          fontSize: '12px'
        },
        style: {
          width: '100%',
          height: '100%',
          backgroundColor: 'rgb(220,220,220)'
        }
      },
      diamond: {
        label: "",
        shape: "diamond",
        coreStyle: {
          width: "80px",
          height: "80px",
          zIndex: "2"
        },
        labelStyle: {
          alignItems: "center",
          justifyContent: "center",
          textAlign:"center",
          fontSize: '12px'
        },
        style: {
          fill: 'rgb(220,220,220)'
        }
      }
    },
    ...options
  }
  this.init();
},
    SimpleDraw.prototype.upDateOption = function(options={}){
      this.options = Object.assign(this.options,options);
      var dragEle = document.querySelectorAll(".DRAGELE");
      if(!this.options.edit){
        [].forEach.call(dragEle,(item)=>{
          this.css(item,{
            style:{
              userSelect:'none'
            }
          })
        })
      }else{
        [].forEach.call(dragEle,(item)=>{
          this.css(item,{
            style:{
              userSelect:'auto'
            }
          })
        })
      }
    }
SimpleDraw.prototype.init = function () {

  if (!this.options.el) {
    throw `缺少el参数，绘图容器ID`;
  }

  var container = document.getElementById(this.options.el);

  if (!container) {
    throw `绘图容器获取失败，请确认el是否传递正确`;
  }

  this.dropSpace = document.createElement("div");
  this.dropSpace.className = "drop-space simple-draw-space";
  this.dropSpace.style.cssText = "flex:1;position:relative;overflow:hidden;width:100%;height:100%;background-image: url();";

  // 定位基准和平移区域
  this.workSpace = document.createElement("div");
  this.workSpace.className = "work-space";
  //this.workSpace.style.pointerEvents = this.options.edit ? "auto" : "none"; //导致无法选中方框

  // 缩放区域
  this.rangeSpace = document.createElement("div");
  this.rangeSpace.className="range-space";
  this.rangeSpace.style.cssText="width:100%;height:100%;transform-origin:center center;";

  // svg区域
  this.svgspace = document.createElementNS("http://www.w3.org/2000/svg", "svg");
  this.svgspace.setAttribute("class", "svg-space");
  this.svgspace.setAttribute("style", "overflow: visible;width:100%;height:100%;position:absolute;");

  // 创建缩放模块
  if(this.options.scale){
    var rangeDiv = this.createRange();
    container.appendChild(rangeDiv);
  }

  this.rangeSpace.appendChild(this.svgspace);
  this.workSpace.appendChild(this.rangeSpace);
  this.dropSpace.appendChild(this.workSpace);
  container.appendChild(this.dropSpace);
  if (this.options.edit) {
    this.drop();
    this.dragAble();
    this.colorPick();
    this.createCoreResize();
  }
  this.workSpaceMove();
}
SimpleDraw.prototype.createRange = function(){
  var rangeDiv = document.createElement("div");
  rangeDiv.className="range";
  rangeDiv.style.cssText="position:absolute;right:10px;bottom:10px;z-index:10;opacity:0.7";
  this.rangeInput = document.createElement("input");
  this.css(this.rangeInput,{
    attribute:{
      type:"range",
      min:'0.1',
      max:'1',
      step:'0.01',
      value:'1'
    }
  })
  this.rangeInput.addEventListener("input",(event)=>{
    this.scaleValue = event.currentTarget.value;
    this.css(this.rangeSpace,{
      style:{
        transform:"scale("+this.scaleValue+")"
      }
    })
  },false)
  rangeDiv.appendChild(this.rangeInput);
  return rangeDiv;
}
SimpleDraw.prototype.workSpaceMove = function () {
  const _this = this;
  var x, y;
  this.dropSpace.addEventListener("mousedown", ($evt) => {
    document.body.style.userSelect = "none";
    this.dropSpace.classList.add("drag-move");
    this.dropSpace.style.cursor = "move";
    x = $evt.clientX - this.getTranslate(this.workSpace, 'x');
    y = $evt.clientY - this.getTranslate(this.workSpace, 'y');
    document.body.addEventListener("mousemove", move, false);
    document.body.addEventListener("mouseup", function up() {
      document.body.style.userSelect = "auto";
      _this.dropSpace.classList.remove("drag-move");
      _this.dropSpace.style.cursor = "default";
      document.body.removeEventListener("mousemove", move);
      document.body.removeEventListener("mouseup", up);
    }, false)
  }, false)

  function move($evt) {
    var mx = $evt.clientX;
    var my = $evt.clientY;
    var transX = mx - x;
    var transY = my - y;
    var translate = "translate3d(" + transX + "px," + transY + "px,0px)";
    _this.css(_this.workSpace, {
      style: {
        "transform": translate
      }
    })
  }
}
SimpleDraw.prototype.drop = function () {
  this.leaveTimer = null;
  this.dropSpace.addEventListener("dragenter", () => {
    this.INDARGAREA = true;
  }, false)
  this.dropSpace.addEventListener("dragleave", () => {
    clearTimeout(this.leaveTimer);
    this.leaveTimer = null;
    this.leaveTimer = setTimeout(() => {
      this.INDARGAREA = false;
    }, 100)
  }, false)
  this.dropSpace.addEventListener('dragover', ($evt) => {
    $evt.preventDefault();
    clearTimeout(this.leaveTimer);
    this.leaveTimer = null;
    this.INDARGAREA = true;
  }, false);
  this.dropSpace.addEventListener("drop", ($evt) => {
    $evt.preventDefault();
    var boolean = null;
    var type = $evt.dataTransfer.getData('text/plain');
    var json = $evt.dataTransfer.getData('text/json') ? JSON.parse($evt.dataTransfer.getData('text/json')) : {};
    var dragEleKey = $evt.dataTransfer.getData('text/dom');
    var shape = $evt.dataTransfer.getData('text/shape') || "custom";

    if (type == 'insert') {
      var coreId = "core" + this.timeStamp();
      this.json.core[coreId] = this.deepClone(this.options.core[shape], true);
      this.json.core[coreId].id = coreId;
      let left;
      let top
      if(this.options.scale){
        // 开启缩放
        let cLeft = this.workSpace.offsetWidth/2;
        let cTop = this.workSpace.offsetHeight/2;
        left = (($evt.layerX - json.mx - this.getTranslate(this.workSpace, 'x'))-cLeft*(1-this.scaleValue))/this.scaleValue;
        top = (($evt.layerY - json.my - this.getTranslate(this.workSpace, 'y'))-cTop*(1-this.scaleValue))/this.scaleValue;
      }else{
        // 未开启缩放
        left = $evt.layerX - json.mx - this.getTranslate(this.workSpace, 'x');
        top = $evt.layerY - json.my - this.getTranslate(this.workSpace, 'y');
      }
      this.json.core[coreId].coreStyle.left = left;
      this.json.core[coreId].coreStyle.top = top;

      if (this.createFun && typeof this.createFun == 'function') {
        boolean = this.createFun({
          id: coreId,
          left: this.json.core[coreId].coreStyle.left,
          top: this.json.core[coreId].coreStyle.top,
          label: this.json.core[coreId].label,
          bind: this.json.core[coreId].bind || {}
        });
      }
      if (typeof boolean == 'boolean' && !boolean) {
        delete this.json.core[coreId];
        return;
      }

      var core = this.createCore(coreId);
      this.rangeSpace.appendChild(core);
      this.setActiveClass(core);
    } else if (type == "move") {
      var left, top;
      this.json.core[dragEleKey]['cpoints'].style.transform = "";
      this.json.core[dragEleKey]['elabel'].style.transform = "";
      this.json.core[dragEleKey]['ele'].style.transform = "";
      if ($evt.target.classList.contains('workspace')) {
        left = $evt.layerX - json.mx;
        top = $evt.layerY - json.my;
      } else {
        var rect = this.workSpace.getBoundingClientRect();
        left = $evt.clientX - rect.left - json.mx;
        top = $evt.clientY - rect.top - json.my;
      }
      if(this.options.scale){
        let cLeft = this.workSpace.offsetWidth/2;
        let cTop = this.workSpace.offsetHeight/2;
        left = (left - cLeft*(1-this.scaleValue))/this.scaleValue;
        top = (top - cTop*(1-this.scaleValue))/this.scaleValue;
      }

      this.json.core[dragEleKey].coreStyle['left'] = left;
      this.json.core[dragEleKey].coreStyle['top'] = top;
      this.json.core[dragEleKey]['ele'].style.left = left + 'px';
      this.json.core[dragEleKey]['ele'].style.top = top + 'px';
      this.json.core[dragEleKey]['cpoints'].style.left = left + 'px';
      this.json.core[dragEleKey]['cpoints'].style.top = top + 'px';
      this.json.core[dragEleKey]['elabel'].style.top = top + 'px';
      this.json.core[dragEleKey]['elabel'].style.left = left + 'px';
    } else {
      return;
    }
  }, false)
}
SimpleDraw.prototype.dragAble = function () {
  var dragEle = document.getElementsByClassName("DRAGELE");
  Array.prototype.forEach.call(dragEle, (ele, index) => {
    var key = 'drag_' + this.timeStamp();
    this.dragEles[key] = ele;
    ele.addEventListener("dragstart", ($evt) => {
      $evt.dataTransfer.effectAllowed = this.options.effectAllowed || 'copy';
      var json = {
        mx: $evt.offsetX || $evt.layerX,
        my: $evt.offsetY || $evt.layerY
      };
      $evt.dataTransfer.setData('text/plain', 'insert');
      $evt.dataTransfer.setData('text/json', JSON.stringify(json));
      $evt.dataTransfer.setData('text/dom', key);
      $evt.dataTransfer.setData('text/shape', ele.getAttribute("data-shape"));
    }, false)
  })
}
SimpleDraw.prototype.timeStamp = function () {
  var date = new Date();
  return date.getTime();
}
SimpleDraw.prototype.on = function (event, fun) {
  switch (event) {
    case 'click':
      this.clickFun = fun;
      break;
    case 'delete':
      this.deleteFun = fun;
      break;
    case 'create':
      this.createFun = fun;
      break;
  }
}
SimpleDraw.prototype.clear = function () {
  for(var x in this.json.core){
    this.deleteCore(x);
  }
}
SimpleDraw.prototype.createCore = function (coreId) {
  var cloneNode, json, client;
  var div = document.createElement("div");
  this.json.core[coreId]['ele'] = div;
  this.json.core[coreId]['lines'] = this.json.core[coreId]['lines'] ? this.json.core[coreId]['lines'] : [];
  div.className = "core";
  div.id = coreId;
  div.setAttribute("tabindex", 1);
  this.css(div, {
    style: this.json.core[coreId].coreStyle
  });
  if (this.json.core[coreId].shape) {
    var shape = document.createElement("div");
    switch (this.json.core[coreId].shape) {
      case "rect":
        var shape = document.createElement("div");
        shape.style.borderRadius = "5px";
        break;
      case "circle":
        var shape = document.createElement("div");
        shape.style.borderRadius = "100%";
        break;
      case "diamond":
        var svg = document.createElementNS("http://www.w3.org/2000/svg", 'svg');
        svg.style.cssText = "width:100%;height:100%;"
        var shape = document.createElementNS("http://www.w3.org/2000/svg", 'path');
        var style = this.json.core[coreId].coreStyle;
        var d = 'M' + parseInt(style.width) / 2 + ',0 L' + parseInt(style.width) + ',' + parseInt(style.height) / 2 + ' L' + parseInt(style.width) / 2 + ',' + parseInt(style.height) + ' L0,' + parseInt(style.height) / 2 + ' z'
        shape.setAttribute("d", d);
        svg.appendChild(shape)
        break;
      default:
        shape.style.borderRadius = "0"
        break;
    }
    this.json.core[coreId].view = shape;
    this.css(shape, {
      style: this.json.core[coreId].style
    })
    if (this.json.core[coreId].shape != "diamond") {
      shape.style.width = "100%";
      shape.style.height = "100%";
      shape.style.boxSizing = "border-box";
      div.appendChild(shape);
    } else {
      div.appendChild(svg);
    }
  } else {}
  this.json.core[coreId]['cpoints'] = this.createCoreDot({
    'coreId': coreId
  });
  this.json.core[coreId]['elabel'] = this.createCoreLabel({
    'coreId': coreId
  });
  if (this.options.edit) {
    div.draggable = true;
    if(this.json.core[coreId].edit != false){
      this.createSetDEl({
        'coreId': coreId,
        'ele': div
      });
    }
    div.addEventListener("dragstart", ($evt) => {
      $evt.stopPropagation();
      $evt.dataTransfer.effectAllowed = 'move';
      json = {
        mx: ($evt.offsetX || $evt.layerX)*this.scaleValue,
        my: ($evt.offsetY || $evt.layerY)*this.scaleValue
      };
      client = {
        mx: $evt.clientX,
        my: $evt.clientY
      }
      $evt.dataTransfer.setData('text/plain', 'move');
      $evt.dataTransfer.setData('text/json', JSON.stringify(json));
      $evt.dataTransfer.setData('text/dom', coreId);
      div.style.opacity = 0;
      this.json.core[coreId]['cpoints'].style.pointerEvents = "none";
      cloneNode = div.cloneNode(true);
      cloneNode.style.opacity = 1;
      cloneNode.style.zIndex = 1;
      cloneNode.style.pointerEvents = "none";
      cloneNode.style.willChange = "transform";
      this.rangeSpace.appendChild(cloneNode);
    })
    div.addEventListener("drag", ($evt) => {
      if (!this.INDARGAREA) {
        //如果在非拖拽区域释放拖拽
        return;
      }
      var translateX = $evt.clientX - client.mx;
      var translateY = $evt.clientY - client.my;
      if(this.options.scale){
        translateX = translateX/this.scaleValue;
        translateY = translateY/this.scaleValue;
      }
      var translate = "translate3d(" + (translateX) + "px," + (translateY) + "px,0)"
      this.json.core[coreId]['cpoints'].style.transform = translate;
      this.json.core[coreId]['elabel'].style.transform = translate;
      cloneNode.style.transform = translate;
      div.style.transform = translate;
      this.updateLine(coreId);
    }, false)
    div.addEventListener("dragend", ($evt) => {
      this.json.core[coreId]['cpoints'].style.pointerEvents = "auto";
      this.json.core[coreId]['cpoints'].style.transform = "";
      this.json.core[coreId]['elabel'].style.transform = "";
      div.style.transform = "";
      div.style.opacity = 1;
      this.rangeSpace.removeChild(cloneNode);
      this.updateLine(coreId);
    }, false)
  }
  // 阻止事件冒泡
  div.addEventListener("mousedown", ($evt) => {
    $evt.stopPropagation();
  }, false)
  div.addEventListener("click", (event) => {
    this.setActiveClass(div);
    if (this.clickFun && typeof this.clickFun == 'function') {
      this.clickFun(event, {
        id: coreId,
        left: this.json.core[coreId].coreStyle.left,
        top: this.json.core[coreId].coreStyle.top,
        label: this.json.core[coreId].label,
        bind: this.json.core[coreId].bind || {}
      });
    }
  }, false)
  return div;
}
SimpleDraw.prototype.setActiveClass = function(div){
  for(var x in this.json.core){
    this.json.core[x].ele.classList.remove("active");
    div.classList.add('active');
  }
}
SimpleDraw.prototype.changeCoreColor = function (id, color) {
  for (var x in this.json.core[id].style) {
    if (x == 'fill' || x == 'backgroundColor') {
      this.json.core[id].style[x] = color;
      this.json.core[id].view.style[x] = color;
    }
  }
}
SimpleDraw.prototype.changeAttribute = function (type,id,attr,value) {
  var attribute = this.json[type][id][attr] ? this.json[type][id][attr] : {};
  this.json[type][id][attr] = (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') ? value : Object.assign(attribute,value);
  if(type == 'core' && attr == 'edit'){
    if(value == false){
      this.json[type][id].ele.querySelector(".delete").style.display="none";
    }else{
      this.json[type][id].ele.querySelector(".delete").style.display="block";
    }
  }
}
SimpleDraw.prototype.updateLine = function (id) {
  var lines = this.json.core[id].lines;
  lines.forEach((item, index) => {
    this.setLine(item);
  }, false)
}
SimpleDraw.prototype.createLine = function (lineId) {
  this.LINE.setAttribute("id", lineId);
  var g = document.createElementNS("http://www.w3.org/2000/svg", "g");
  g.setAttribute("id", lineId + '_g');
  g.setAttribute("class", 'svg-line-g');
  g.innerHTML = '<defs>' +
      '<marker id="' + lineId + '_arrow' + '" viewBox="0 0 20 20" markerWidth="10" markerHeight="10" orient="auto" refX="11" refY="10">' +
      '<path id="' + lineId + '_arrow_path' + '" d="M 1 5 L 11 10 L 1 15 Z" style="stroke-width: 1; stroke-linecap: round; stroke-dasharray: 10000, 1;" fill="'+ (this.json.line[lineId].style.stroke || "#58cbf7") +'"></path>' +
      '</marker>' +
      '</defs>';
  this.LINE.setAttribute("class","line");
  this.LINE.style.markerEnd = "url('#" + lineId + '_arrow' + "')";
  this.LINE.style.pointerEvents = "none";

  var lineUnder = document.createElementNS("http://www.w3.org/2000/svg", "path");
  this.css(lineUnder,{
    style:{
      "strokeWidth":'12px',
      "stroke":"rgba(0,0,0,0)",
      "shape-rendering": 'geometricPrecision',
      "stroke-linecap":"round"
    },
    attribute:{
      id:lineId+'_under',
      class:"line_under",
      fill:"none"
    }
  })

  if (this.options.edit) {
    lineUnder.addEventListener("contextmenu", ($evt) => {
      $evt.preventDefault();
      this.contextmenu({
        type: "line",
        dom: lineId,
        event: $evt
      });
      return false;
    }, false)
  }
  g.appendChild(lineUnder);
  g.appendChild(this.LINE);
  this.svgspace.appendChild(g);
  this.setLine(lineId);
}
SimpleDraw.prototype.setLine = function (item) {
  var line = this.json.line[item];
  var fromCore = this.workSpace.querySelector("#" + line['ft'][0]);
  var toCore = this.workSpace.querySelector("#" + line['ft'][1]);

  var fromDirection = this.getLineFormTo(fromCore, toCore);
  var toDirection = this.getLineFormTo(toCore, fromCore);
  var from = line['ft'][0] + '_dot_' + fromDirection;
  var to;
  switch (line.type) {
    case 'line':
      to = line['ft'][1] + '_dot_' + toDirection;
      break;
    case 'brokeline':
      if (fromDirection == 'top' || fromDirection == 'bottom') {
        if ((fromCore.offsetLeft + this.getTranslate(fromCore, 'x') + fromCore.offsetWidth / 2) > (toCore.offsetLeft + this.getTranslate(toCore, 'x') + toCore.offsetWidth)) {
          to = line['ft'][1] + '_dot_' + 'right';
        } else if ((fromCore.offsetLeft + this.getTranslate(fromCore, 'x') + fromCore.offsetWidth / 2) < (toCore.offsetLeft + this.getTranslate(toCore, 'x'))) {
          to = line['ft'][1] + '_dot_' + 'left';
        } else {
          to = line['ft'][1] + '_dot_' + toDirection;
        }
      } else if (fromDirection == 'right' || fromDirection == 'left') {
        if ((fromCore.offsetTop + this.getTranslate(fromCore, 'y') + fromCore.offsetHeight / 2) > (toCore.offsetTop + this.getTranslate(toCore, 'y') + toCore.offsetHeight)) {
          to = line['ft'][1] + '_dot_' + 'bottom';
        } else if ((fromCore.offsetTop + this.getTranslate(fromCore, 'y') + fromCore.offsetHeight / 2) < (toCore.offsetTop + this.getTranslate(toCore, 'y'))) {
          to = line['ft'][1] + '_dot_' + 'top';
        } else {
          to = line['ft'][1] + '_dot_' + toDirection;
        }
      } else {
        to = line['ft'][1] + '_dot_' + toDirection;
      }
      break;
    case 'polyline':
      to = line['ft'][1] + '_dot_' + toDirection;
      break;
  }
  line.fromTo = [from, to];
  this.drawLine(line);
},
    SimpleDraw.prototype.drawLine = function (line) {
      var sDom = this.workSpace.querySelector("#" + line.fromTo[0]);
      var eDom = this.workSpace.querySelector("#" + line.fromTo[1]);
      var sParent = sDom.parentNode;
      var eParent = eDom.parentNode;
      var sDomLeft = sDom.offsetLeft + sParent.offsetLeft + this.getTranslate(sParent, 'x');
      var sDomTop = sDom.offsetTop + sParent.offsetTop + this.getTranslate(sParent, 'y');
      var eDomLeft = eDom.offsetLeft + eParent.offsetLeft + this.getTranslate(eParent, 'x');
      var eDomTop = eDom.offsetTop + eParent.offsetTop + this.getTranslate(eParent, 'y');
      var M = "M" + sDomLeft + ',' + sDomTop;
      var E = " L" + eDomLeft + ',' + eDomTop;
      switch (line.type) {
        case 'line':
          var d = M + E;
          break;
        case 'brokeline':
          if (line.fromTo[0].split("_")[2] == 'left' || line.fromTo[0].split("_")[2] == 'right') {
            if (line.fromTo[1].split("_")[2] == "top" || line.fromTo[1].split("_")[2] == "bottom") {
              var L1 = " L" + eDomLeft + ',' + sDomTop;
            } else {
              var L1 = " L" + ((eDomLeft - sDomLeft) / 2 + sDomLeft) + ',' + sDomTop;
              var L2 = " L" + ((eDomLeft - sDomLeft) / 2 + sDomLeft) + ',' + eDomTop;
            }
          } else {
            if (line.fromTo[1].split("_")[2] == "left" || line.fromTo[1].split("_")[2] == "right") {
              var L1 = " L" + sDomLeft + ',' + eDomTop;
            } else {
              var L1 = " L" + sDomLeft + ',' + ((sDomTop - eDomTop) / 2 + eDomTop);
              var L2 = " L" + eDomLeft + ',' + ((sDomTop - eDomTop) / 2 + eDomTop);
            }
          }
          var d = M + L1 + (L2 ? L2 : '') + E;
          break;
        case 'polyline':
          if (line.fromTo[0].split("_")[2] == 'left' || line.fromTo[0].split("_")[2] == 'right') {
            var L1 = " L" + ((eDomLeft - sDomLeft) / 2 + sDomLeft) + ',' + sDomTop;
            var L2 = " L" + ((eDomLeft - sDomLeft) / 2 + sDomLeft) + ',' + eDomTop;
          } else {
            var L1 = " L" + sDomLeft + ',' + ((sDomTop - eDomTop) / 2 + eDomTop);
            var L2 = " L" + eDomLeft + ',' + ((sDomTop - eDomTop) / 2 + eDomTop);
          }
          var d = M + L1 + L2 + E;
          break;
      }
      this.workSpace.querySelector("#" + line.id).setAttribute("d", d);
      this.workSpace.querySelector("#" + line.id+'_under').setAttribute("d", d);
    }
SimpleDraw.prototype.changeLineType = function (type, id) {
  this.json.line[id].type = type;
  this.setLine(id);
}
SimpleDraw.prototype.changeLineColor = function (id, color) {
  this.json.line[id].style.stroke = color;
  this.workSpace.querySelector("#" + id).style.stroke = color;
  this.workSpace.querySelector("#" + id + '_arrow_path').style.fill = color;
}
SimpleDraw.prototype.createCoreResize = function () {
  const _this = this;
  var type, svgLeft, svgTop;
  var spans = ['top-left', 'top', 'top-right', 'right', 'bottom-right', 'bottom', 'bottom-left', 'left'];
  var cursor = ['nw-resize', 'n-resize', 'ne-resize', 'e-resize', 'se-resize', 's-resize', 'sw-resize', 'w-resize'];
  var g = document.createElementNS("http://www.w3.org/2000/svg", "g");
  g.setAttribute("display", 'none');
  this.resize['g'] = g;
  var path = document.createElementNS("http://www.w3.org/2000/svg", "path");
  this.resize['path'] = path;
  //path.style.pointerEvents="none";
  path.addEventListener("mousedown", ($evt) => {
    $evt.stopPropagation();
  }, false)
  path.setAttribute("fill", 'rgba(0,0,0,0)');
  path.setAttribute("stroke", '#4F80FF');
  path.setAttribute("shape-rendering", 'crispEdges');
  g.appendChild(path);
  spans.forEach((item, index) => {
    var x = 0;
    var y = 0;
    var rect = document.createElementNS("http://www.w3.org/2000/svg", "rect");
    rect.setAttribute("width", 8);
    rect.setAttribute("height", 8);
    rect.setAttribute("fill", "rgb(5,106,220)");
    rect.setAttribute("class", item);
    this.resize[item] = rect;
    rect.style.cursor = cursor[index];
    rect.addEventListener("mousedown", ($evt) => {
      $evt.stopPropagation();
      var rec = this.workSpace.getBoundingClientRect();
      type = item;
      svgLeft = rec.x;
      svgTop = rec.y;
      this.resize.path.setAttribute("fill", "rgba(88, 203, 247,0.3)");
      document.body.addEventListener("mousemove", move, false);
      document.body.addEventListener("mouseup", mouseup, false);
    }, false);
    g.appendChild(rect);
  })
  this.svgspace.appendChild(g);

  function mouseup($evt) {
    _this.resize.path.setAttribute("fill", "rgba(0,0,0,0)");
    _this.resetSizePos();
    document.body.removeEventListener('mousemove', move);
    document.body.removeEventListener('mouseup', mouseup);
  };

  function move($evt) {
    var mx = $evt.clientX;
    var my = $evt.clientY;
    _this.coreResizeChange(mx - svgLeft, my - svgTop, type);
  }
}
SimpleDraw.prototype.coreResizeChange = function (x, y, item) {
  var min = this.min;
  switch (item) {
    case 'top-left':
      var cY = Number(this.resize['bottom-right'].getAttribute("y")) + 4;
      var cX = Number(this.resize['bottom-right'].getAttribute("x")) + 4;
      if (y >= cY - min) {
        y = cY - min;
      }
      if (x >= cX - min) {
        x = cX - min;
      }
      var w = Math.abs(cX - x);
      var h = Math.abs(y - cY);
      this.coreResizeMethod(x, y, w, h);
      break;
    case 'top':
      var cY = Number(this.resize['bottom-left'].getAttribute("y")) + 4;
      var cX = Number(this.resize['bottom-left'].getAttribute("x")) + 4;
      if (y >= cY - min) {
        y = cY - min;
      }
      var w = Math.abs(Number(this.resize['bottom-right'].getAttribute("x")) + 4 - cX);
      var h = Math.abs(y - cY);
      this.coreResizeMethod(cX, y, w, h);
      break;
    case 'top-right':
      var cY = Number(this.resize['bottom-left'].getAttribute("y")) + 4;
      var cX = Number(this.resize['bottom-left'].getAttribute("x")) + 4;
      if (y >= cY - min) {
        y = cY - min;
      }
      if (x <= cX + min) {
        x = cX + min;
      }
      var w = Math.abs(x - cX);
      var h = Math.abs(y - cY);
      this.coreResizeMethod(x - w, y, w, h);
      break;
    case 'right':
      var cY = Number(this.resize['top-left'].getAttribute("y")) + 4;
      var cX = Number(this.resize['top-left'].getAttribute("x")) + 4;
      if (x <= cX + min) {
        x = cX + min;
      }
      var w = Math.abs(x - cX);
      var h = Math.abs(Number(this.resize['bottom-left'].getAttribute("y")) + 4 - cY);
      this.coreResizeMethod(cX, cY, w, h);
      break;
    case 'bottom-right':
      var cY = Number(this.resize['top-left'].getAttribute("y")) + 4;
      var cX = Number(this.resize['top-left'].getAttribute("x")) + 4;
      if (y <= cY + min) {
        y = cY + min;
      }
      if (x <= cX + min) {
        x = cX + min;
      }
      var w = Math.abs(x - cX);
      var h = Math.abs(y - cY);
      this.coreResizeMethod(cX, cY, w, h);
      break;
    case 'bottom':
      var cY = Number(this.resize['top-left'].getAttribute("y")) + 4;
      var cX = Number(this.resize['top-left'].getAttribute("x")) + 4;
      if (y <= cY + min) {
        y = cY + min;
      }
      var w = Math.abs(Number(this.resize['bottom-right'].getAttribute("x")) + 4 - cX);
      var h = Math.abs(y - cY);
      this.coreResizeMethod(cX, cY, w, h);
      break;
    case 'bottom-left':
      var cY = Number(this.resize['top-right'].getAttribute("y")) + 4;
      var cX = Number(this.resize['top-right'].getAttribute("x")) + 4;
      if (y <= cY + min) {
        y = cY + min;
      }
      if (x >= cX - min) {
        x = cX - min;
      }
      var w = Math.abs(cX - x);
      var h = Math.abs(y - cY);
      this.coreResizeMethod(x, cY, w, h);
      break;
    case 'left':
      var cY = Number(this.resize['top-right'].getAttribute("y")) + 4;
      var cX = Number(this.resize['top-right'].getAttribute("x")) + 4;
      if (x >= cX - min) {
        x = cX - min;
      }
      var w = Math.abs(cX - x);
      var h = Math.abs(Number(this.resize['bottom-right'].getAttribute("y")) + 4 - cY);
      this.coreResizeMethod(x, cY, w, h);
      break;
  }
}
SimpleDraw.prototype.showCoreResize = function (param) {
  const _this = this;
  this.RESIZECORE = param.coreId;
  var core = this.json.core[param.coreId];
  var x = core.ele.offsetLeft;
  var y = core.ele.offsetTop;
  var w = core.ele.offsetWidth;
  var h = core.ele.offsetHeight;
  this.coreResizeMethod(x, y, w, h);
  this.resize.g.setAttribute("display", "block");
  this.svgspace.style.zIndex = "3";
  document.body.addEventListener("mousedown", function hideg() {
    _this.svgspace.style.zIndex = "1";
    _this.resize.g.setAttribute("display", "none");
    document.body.removeEventListener("mousedown", hideg);
  }, false)
}
SimpleDraw.prototype.coreResizeMethod = function (x, y, w, h) {
  var M = "M" + x + "," + y;
  var L1 = " L" + (x + w) + "," + y;
  var L2 = " L" + (x + w) + "," + (y + h);
  var L3 = " L" + x + "," + (y + h);
  this.resize.path.setAttribute("d", M + L1 + L2 + L3 + " z");

  this.resize['top-left'].setAttribute("x", x - 4);
  this.resize['top-left'].setAttribute("y", y - 4);

  this.resize['top'].setAttribute("x", x + w / 2 - 4);
  this.resize['top'].setAttribute("y", y - 4);

  this.resize['top-right'].setAttribute("x", x + w - 4);
  this.resize['top-right'].setAttribute("y", y - 4);

  this.resize['right'].setAttribute("x", x + w - 4);
  this.resize['right'].setAttribute("y", y + h / 2 - 4);

  this.resize['bottom-right'].setAttribute("x", x + w - 4);
  this.resize['bottom-right'].setAttribute("y", y + h - 4);

  this.resize['bottom'].setAttribute("x", x + w / 2 - 4);
  this.resize['bottom'].setAttribute("y", y + h - 4);

  this.resize['bottom-left'].setAttribute("x", x - 4);
  this.resize['bottom-left'].setAttribute("y", y + h - 4);

  this.resize['left'].setAttribute("x", x - 4);
  this.resize['left'].setAttribute("y", y + h / 2 - 4);
}
SimpleDraw.prototype.resetSizePos = function () {
  var core = this.json.core[this.RESIZECORE];
  var x = Number(this.resize['top-left'].getAttribute("x")) + 4;
  var y = Number(this.resize['top-left'].getAttribute("y")) + 4;
  var w = Number(this.resize['top-right'].getAttribute("x")) - Number(this.resize['top-left'].getAttribute("x"));
  var h = Number(this.resize['bottom-left'].getAttribute("y")) - Number(this.resize['top-left'].getAttribute("y"));

  core.coreStyle.left = x;
  core.coreStyle.top = y;
  core.coreStyle.width = w;
  core.coreStyle.height = h;

  this.css(core['cpoints'], {
    style: {
      width: w,
      height: h,
      left: x,
      top: y
    }
  })
  this.css(core['elabel'], {
    style: {
      width: w,
      height: h,
      left: x,
      top: y
    }
  })
  this.css(core.ele, {
    style: core.coreStyle
  });

  switch (this.json.core[this.RESIZECORE].shape) {
    case 'diamond':
      var path = "M" + w / 2 + ",0" +
          " L" + w + "," + h / 2 +
          " L" + w / 2 + "," + h +
          " L0," + h / 2 +
          " z"
      this.json.core[this.RESIZECORE].view.setAttribute("d", path);
      break;
  }
  this.updateLine(this.RESIZECORE);
}
SimpleDraw.prototype.createCoreDot = function (param) {
  var coreStyle = this.json.core[param.coreId].coreStyle;
  var line;
  var spans = ['top', 'right', 'bottom', 'left'];
  var div = document.createElement("div");
  div.className = "dot-line";
  div.id = param.coreId + "_dot";
  var style = {
    style: {
      willChange: "transform",
      position: "absolute",
      width: coreStyle.width + (typeof coreStyle.width == "string" ? '' : "px"),
      height: coreStyle.height + (typeof coreStyle.height == "string" ? '' : "px"),
      left: coreStyle.left + (typeof coreStyle.left == "string" ? '' : "px"),
      top: coreStyle.top + (typeof coreStyle.top == "number" ? 'px' : ''),
      borderRadius: this.json.core[param.coreId].shape == 'rect' ? '5px' : '100%'
    }
  }
  this.css(div, style);
  spans.forEach((item, index) => {
    var key = param.coreId + "_dot_" + item;
    var span = document.createElement("span");
    span.className = item;
    span.id = key;
    div.appendChild(span);
  })

  // 阻止事件冒泡
  div.addEventListener("mousedown", ($evt) => {
    $evt.stopPropagation();
  }, false)

  div.addEventListener("drop", ($evt) => {
    $evt.preventDefault();
    $evt.dataTransfer.dropEffect = 'move';
    div.classList.remove("dragenter");
    var type = $evt.dataTransfer.getData('text/plain');
    var fromId = $evt.dataTransfer.getData('text/dom');
    if (type == 'drawline' && fromId) {
      if (fromId != param.coreId) {
        if (this.LINE) {
          // 验证是否重复连接
          for (var x in this.json.line) {
            if (this.json.line[x]['ft'][0] == fromId && this.json.line[x]['ft'][1] == param.coreId) {
              alert("不能重复连接")
              return false;
            }
          }

          var timeStamp = this.timeStamp();
          var lineId = 'line' + timeStamp;

          var fromD = fromId + '_dot_' + this.getLineFormTo(this.json.core[fromId].ele, this.json.core[param.coreId].ele);
          var toD = param.coreId + '_dot_' + this.getLineFormTo(this.json.core[param.coreId].ele, this.json.core[fromId].ele);

          this.json.core[fromId].lines.push(lineId);
          this.json.core[param.coreId].lines.push(lineId);

          this.json.line[lineId] = {
            id: lineId,
            fromTo: [fromD, toD],
            ft: [fromId, param.coreId],
            style: {
              ...this.options.line.style
            },
            type: "line"
          };

          this.createLine(lineId);

          this.CREATELINESUCCESS = true;
        }
      }
    }
  }, false)

  div.addEventListener("dragenter", () => {
    if (this.FROMCORE && this.FROMCORE != param.coreId) {
      div.classList.add("dragenter");
    }
  }, false)

  div.addEventListener("dragleave", () => {
    div.classList.remove("dragenter");
  }, false)

  if (this.options.edit) {
    var linkpoint = document.createElement("div");
    linkpoint.draggable = true;
    linkpoint.className = "link-pointer";
    linkpoint.id = param.coreId + "_dot_linkpoint";
    linkpoint.style.cssText = "position:absolute;right:-20px;top:-20px;";
    linkpoint.innerHTML = "<i class='icon-font icon-V' style='font-size:20px;color:#bbb;'></i>";
    linkpoint.addEventListener("dragstart", ($evt) => {
      $evt.stopPropagation();
      this.dropSpace.classList.add("draw-line-ing");
      this.FROMCORE = param.coreId;
      $evt.dataTransfer.effectAllowed = 'move';
      $evt.dataTransfer.setData('text/plain', 'drawline');
      $evt.dataTransfer.setData('text/dom', param.coreId);
      line = document.createElementNS("http://www.w3.org/2000/svg", "path");
      this.css(line, {
        style: this.options.line.style,
        attribute: {
          "shape-rendering": 'geometricPrecision'
        }
      })
      // path形式
      var d = "M" +
          (div.offsetLeft + div.offsetWidth / 2) +
          ',' +
          (div.offsetTop + div.offsetHeight / 2) +
          " L" +
          (div.offsetLeft + div.offsetWidth / 2) +
          ',' +
          (div.offsetTop + div.offsetHeight / 2)
      line.setAttribute("d", d)
      this.svgspace.appendChild(line);
      this.LINE = line;
    }, false)
    linkpoint.addEventListener("drag", ($evt) => {
      if (!this.INDARGAREA) {
        //如果在非拖拽区域释放拖拽
        return;
      }
      line.style.pointerEvents = "none";
      // path形式
      var d = "M" +
          (div.offsetLeft + div.offsetWidth / 2) +
          ',' +
          (div.offsetTop + div.offsetHeight / 2) +
          " L" +
          ($evt.offsetX + div.offsetLeft + linkpoint.offsetLeft) +
          ',' +
          ($evt.offsetY + div.offsetTop + linkpoint.offsetTop)
      line.setAttribute("d", d)
    }, false)
    linkpoint.addEventListener("dragend", () => {
      if (!this.CREATELINESUCCESS && this.LINE) {
        this.svgspace.removeChild(this.LINE);
      }
      this.CREATELINESUCCESS = false;
      this.FROMCORE = null;
      this.LINE = null;
      this.dropSpace.classList.remove("draw-line-ing");
    }, false)
    div.appendChild(linkpoint);
  }


  this.rangeSpace.appendChild(div);
  return div;
}
SimpleDraw.prototype.createCoreLabel = function (param) {
  var coreStyle = this.json.core[param.coreId].coreStyle;
  var labelStyle = this.json.core[param.coreId].labelStyle;
  var div = document.createElement("div");
  div.className = "core-label";
  div.id = param.coreId + "_label";
  div.innerHTML = this.json.core[param.coreId].label;
  if(this.json.core[param.coreId].labelAppend){
    var temp = document.createElement("div");
    temp.innerHTML = this.json.core[param.coreId].labelAppend;
    div.appendChild(temp.children[0]);
  }
  var style = {
    style: {
      willChange: "transform",
      display: "flex",
      position: "absolute",
      width: coreStyle.width + (typeof coreStyle.width == "string" ? '' : "px"),
      height: coreStyle.height + (typeof coreStyle.height == "string" ? '' : "px"),
      left: coreStyle.left + (typeof coreStyle.left == "string" ? '' : "px"),
      top: coreStyle.top + (typeof coreStyle.top == "number" ? 'px' : ''),
      zIndex: "3",
      pointerEvents: "none",
      userSelect: "none",
      ...labelStyle
    }
  }
  this.css(div, style);
  this.rangeSpace.appendChild(div);
  return div;
}
SimpleDraw.prototype.changeCoreLabel = function (id, label) {
  this.json.core[id].label = label;
  this.json.core[id].elabel.innerHTML = label;
}
SimpleDraw.prototype.changeLabelColor = function (id, color) {
  this.json.core[id].labelStyle.color = color;
  this.css(this.workSpace.querySelector("#" + id + '_label'), {
    style: this.json.core[id].labelStyle
  });
}
SimpleDraw.prototype.css = function (ele, style) {
  for (var x in style) {
    switch (x) {
      case 'attribute':
        for (var key in style[x]) {
          ele.setAttribute(key, style[x][key]);
        }
        break;
      case 'style':
        for (var key in style[x]) {
          ele.style[key] = style[x][key] + (typeof style[x][key] == "number" ? 'px' : '');
        }
        break;
    }
  }
}
SimpleDraw.prototype.createSetDEl = function (param) {
  var set = document.createElement("div");
  set.innerHTML = '<i class="icon-font icon-setting"></i>'
  set.className = "setting";
  set.style.position = "absolute";
  set.style.left = "0px";
  set.style.top = "0px";
  var div = document.createElement("div");
  var ul = document.createElement("ul");
  div.className = "control-bar";
  ul.innerHTML = '<li class="top"><i class="icon-font icon-jushang" style="pointer-events:none;"></i></li>' +
      '<li class="center"><i class="icon-font icon-juzhong" style="pointer-events:none;"></i></li>' +
      '<li class="bottom"><i class="icon-font icon-juxia" style="pointer-events:none;"></i></li>' +
      '<li class="left"><i class="icon-font icon-T-juzuo" style="pointer-events:none;"></i></li>' +
      '<li class="middle"><i class="icon-font icon-T-juzhong" style="pointer-events:none;"></i></li>' +
      '<li class="right"><i class="icon-font icon-T-juyou" style="pointer-events:none;"></i></li>' +
      '<li class="color"><i class="icon-font icon-zitiyanse" style="pointer-events:none;"></i></li>' +
      '<li class="fill"><i class="icon-font icon-colorSelector" style="pointer-events:none;"></i></li>' +
      '<li class="suofang"><i class="icon-font icon-suofang" style="pointer-events:none;"></i></li>'
  div.addEventListener("click", ($evt) => {
    var ele = $evt.target;
    switch (ele.className) {
      case 'top':
        this.json.core[param.coreId].labelStyle.alignItems = "flex-start";
        this.css(this.workSpace.querySelector("#" + param.coreId + "_label"), {
          style: this.json.core[param.coreId].labelStyle
        });
        break;
      case 'center':
        this.json.core[param.coreId].labelStyle.alignItems = "center";
        this.css(this.workSpace.querySelector("#" + param.coreId + "_label"), {
          style: this.json.core[param.coreId].labelStyle
        });
        break;
      case 'bottom':
        this.json.core[param.coreId].labelStyle.alignItems = "flex-end";
        this.css(this.workSpace.querySelector("#" + param.coreId + "_label"), {
          style: this.json.core[param.coreId].labelStyle
        });
        break;
      case 'left':
        this.json.core[param.coreId].labelStyle.justifyContent = "flex-start";
        this.json.core[param.coreId].labelStyle.textAlign = "left";
        this.css(this.workSpace.querySelector("#" + param.coreId + "_label"), {
          style: this.json.core[param.coreId].labelStyle
        });
        break;
      case 'middle':
        this.json.core[param.coreId].labelStyle.justifyContent = "center";
        this.json.core[param.coreId].labelStyle.textAlign = "center";
        this.css(this.workSpace.querySelector("#" + param.coreId + "_label"), {
          style: this.json.core[param.coreId].labelStyle
        });
        break;
      case 'right':
        this.json.core[param.coreId].labelStyle.justifyContent = "flex-end";
        this.json.core[param.coreId].labelStyle.textAlign = "right";
        this.css(this.workSpace.querySelector("#" + param.coreId + "_label"), {
          style: this.json.core[param.coreId].labelStyle
        });
        break;
      case 'color':
        this.colorPicker.show($evt.clientX, $evt.clientY, param.coreId, 'label');
        break;
      case 'fill':
        this.colorPicker.show($evt.clientX, $evt.clientY, param.coreId, 'core');
        break;
      case 'suofang':
        this.showCoreResize(param);
        break;
    }
  }, false)
  div.appendChild(ul);
  set.appendChild(div);
  var del = document.createElement("div");
  del.innerHTML = '<i class="icon-font icon-shanchu"></i>'
  del.className = "delete";
  del.style.position = "absolute";
  del.style.right = "0px";
  del.style.top = "0px";
  param.ele.appendChild(set);
  param.ele.appendChild(del);

  del.addEventListener("click", ($evt) => {
    $evt.stopPropagation();
    if(this.json["core"][param.coreId].edit == false || this.options.edit == false){
      Message.warning("此模块不能删除");
      return;
    }
    MessageBox.confirm('此操作将永久删除该文件, 是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      var boolean = null;
      if (this.deleteFun) {
        boolean = this.deleteFun({
          id: param.coreId,
          left: this.json.core[param.coreId].coreStyle.left,
          top: this.json.core[param.coreId].coreStyle.top,
          label: this.json.core[param.coreId].label,
          bind: this.json.core[param.coreId].bind || {}
        });
      }
      if (typeof boolean == 'boolean' && !boolean) {
        return;
      }
      this.deleteCore(param.coreId);
    }).catch(() => {
      return;
    });
  }, false);
}
SimpleDraw.prototype.deleteCore = function (coreId) {
  this.clearLine(this.json.core[coreId]['lines']);
  this.rangeSpace.removeChild(this.json.core[coreId]['ele']);
  this.rangeSpace.removeChild(this.json.core[coreId]['elabel']);
  this.rangeSpace.removeChild(this.json.core[coreId]['cpoints']);
  delete this.json.core[coreId];
}
SimpleDraw.prototype.contextmenu = function (param) {
  const that = this;
  that.removeContextmenu();
  var div = document.createElement("div");
  this.CONTEXTMENU = div;
  div.style.position = "fixed";
  div.style.left = param.event.clientX + 'px';
  div.style.top = param.event.clientY + 'px';
  div.className = "simple-draw-context-menu";
  var ul = document.createElement("ul");
  var controls = [{
    icon: '<?xml version="1.0" standalone="no"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><svg t="1610344310393" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="15187" xmlns:xlink="http://www.w3.org/1999/xlink" width="200" height="200"><defs><style type="text/css"></style></defs><path d="M897.969231 842.830769L567.138462 512l330.830769-330.830769-55.138462-55.138462-330.830769 330.830769-330.830769-330.830769-55.138462 55.138462 330.830769 330.830769-330.830769 330.830769 55.138462 55.138462 330.830769-330.830769 330.830769 330.830769z" fill="#ccc" p-id="15188"></path></svg>',
    type: 'delete',
    label: "删除"
  }, {
    icon: '<svg xmlns="http://www.w3.org/2000/svg"><polyline points="0,0 14,14" style="fill:none;stroke:#ccc;stroke-width:1" /></svg>',
    type: "line",
    label: "直线"
  }, {
    icon: '<svg xmlns="http://www.w3.org/2000/svg"><polyline points="0,0 0,14 14,14" style="fill:none;stroke:#ccc;stroke-width:1" /></svg>',
    type: "brokeline",
    label: "折线"
  }, {
    icon: '<svg xmlns="http://www.w3.org/2000/svg"><polyline points="0,0 7,0 7,14 14,14" style="fill:none;stroke:#ccc;stroke-width:1" /></svg>',
    type: "polyline",
    label: "折线2"
  }, {
    icon: '<svg t="1610347408019" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="3881" xmlns:xlink="http://www.w3.org/1999/xlink" width="200" height="200"><defs><style type="text/css"></style></defs><path d="M716.8 897.024c-73.728 0-133.12-59.392-133.12-133.12v-2.048c0-20.48 6.144-45.056 16.384-71.68 0 0 0-2.048 2.048-2.048 12.288-30.72 30.72-61.44 55.296-94.208 16.384-22.528 34.816-45.056 51.2-65.536 2.048-4.096 6.144-6.144 8.192-10.24 2.048 2.048 6.144 6.144 8.192 10.24 6.144 8.192 14.336 16.384 20.48 26.624 8.192 10.24 16.384 22.528 24.576 32.768 2.048 2.048 4.096 4.096 6.144 8.192 24.576 32.768 43.008 67.584 55.296 96.256 12.288 26.624 18.432 51.2 18.432 73.728 0 71.68-59.392 131.072-133.12 131.072z m-546.816-366.592l81.92-88.064h581.632l16.384 16.384-73.728 69.632c-6.144-8.192-12.288-16.384-20.48-24.576-6.144-8.192-12.288-14.336-18.432-20.48-4.096-4.096-6.144-6.144-6.144-8.192l-14.336-16.384-14.336 16.384c-2.048 2.048-4.096 4.096-6.144 8.192-6.144 6.144-12.288 12.288-18.432 20.48-18.432 22.528-36.864 45.056-53.248 69.632-24.576 36.864-45.056 71.68-59.392 104.448-10.24 24.576-16.384 47.104-18.432 67.584l-83.968 77.824-292.864-292.864z m364.544-389.12l260.096 260.096h-501.76l241.664-260.096z m276.48 430.08c-2.048-4.096-6.144-8.192-8.192-12.288l106.496-100.352-376.832-376.832-419.84 448.512 348.16 348.16 86.016-79.872c16.384 79.872 86.016 141.312 169.984 141.312 96.256 0 174.08-77.824 174.08-174.08 0-26.624-8.192-57.344-20.48-88.064-14.336-34.816-34.816-71.68-59.392-106.496z" p-id="3882" fill="#cccccc"></path></svg>',
    type: "color",
    label: "颜色"
  }]
  controls.forEach((item, index) => {
    var li = document.createElement("li");
    li.innerHTML = item.icon + "<span>" + item.label + "</span>";
    li.addEventListener("click", ($evt) => {
      $evt.stopPropagation();
      switch (item.type) {
        case 'delete':
          this.clearLine([param.dom]);
          break;
        case 'line':
          this.changeLineType('line', param.dom);
          break;
        case 'brokeline':
          this.changeLineType('brokeline', param.dom);
          break;
        case 'polyline':
          this.changeLineType('polyline', param.dom);
          break;
        case 'color':
          this.colorPicker.show($evt.clientX, $evt.clientY, param.dom, 'line');
          break;
      }
      this.removeContextmenu();
    }, false)
    li.addEventListener("mousedown", ($evt) => {
      $evt.stopPropagation();
    }, false)
    ul.appendChild(li);
  })
  div.appendChild(ul);
  document.body.appendChild(div);

  document.body.addEventListener("mousedown", function removeContextMenu() {
    that.removeContextmenu();
    document.body.removeEventListener("mousedown", removeContextMenu);
  }, false)
}
SimpleDraw.prototype.removeContextmenu = function () {
  if (this.CONTEXTMENU) {
    document.body.removeChild(this.CONTEXTMENU);
    this.CONTEXTMENU = null;
  }
}
SimpleDraw.prototype.clearLine = function (lines) {
  lines.forEach((val, index) => {
    var item = val;
    if (typeof val != "string") {
      item = val.getAttribute("id");
    }
    for (var x in this.json.core) {
      this.json.core[x].lines = this.json.core[x].lines.filter((val, ind) => {
        return val != item;
      })
    }
    this.svgspace.removeChild(this.workSpace.querySelector("#" + item + '_g'));
    delete this.json.line[item];
  })
}
SimpleDraw.prototype.render = function (options) {
  this.json = Object.assign({
    'core': {},
    'line': {}
  },options);
  var cores = this.json.core;
  var lines = this.json.line;
  for (var x in cores) {
    var core = this.createCore(x);
    this.rangeSpace.appendChild(core);
  }
  for (var l in lines) {
    this.LINE = document.createElementNS("http://www.w3.org/2000/svg", "path");
    this.css(this.LINE, {
      style: {
        ...this.options.line.style,
        ...lines[l].style
      },
      attribute: {
        "shape-rendering": 'geometricPrecision'
      }
    })
    this.createLine(l);
    this.LINE = null;
  }
}
SimpleDraw.prototype.getResult = function () {
  var result = this.deepClone(this.json, true);
  for (var x in result.core) {
    delete result.core[x].ele;
    delete result.core[x].cpoints;
    delete result.core[x].elabel;
    delete result.core[x].view;
  }
  return result;
}
SimpleDraw.prototype.getLineFormTo = function (from, to) {
  var w = from.offsetWidth;
  var h = from.offsetHeight;
  var x = (to.offsetLeft + this.getTranslate(to, 'x') + (to.offsetWidth / 2) - from.offsetLeft - this.getTranslate(from, 'x') - (w / 2)) * (w > h ? (h / w) : 1);
  var y = (to.offsetTop + this.getTranslate(to, 'y') + (to.offsetHeight / 2) - from.offsetTop - this.getTranslate(from, 'y') - (h / 2)) * (h > w ? (w / h) : 1);
  return this.direction(x, y);
}
SimpleDraw.prototype.direction = function (x, y) {
  //结果是0、1、2、3 之间的一个（分别代表上、右、下、左）。
  var map = ['top', 'right', 'bottom', 'left']
  return map[Math.round((((Math.atan2(y, x) * (180 / Math.PI)) + 180) / 90) + 3) % 4];
}
SimpleDraw.prototype.getTranslate = function (node, sty) { //获取transform值
  var translates = document.defaultView.getComputedStyle(node, null).transform.substring(7);
  var result = translates.match(/\(([^)]*)\)/); // 正则()内容
  var matrix = result ? result[1].split(',') : translates.split(',');
  if (sty == "x" || sty == undefined) {
    return matrix.length > 6 ? isNaN(parseFloat(matrix[12])) ? 0 : parseFloat(matrix[12]) : isNaN(parseFloat(matrix[4])) ? 0 : parseFloat(matrix[4]);
  } else if (sty == "y") {
    return matrix.length > 6 ? isNaN(parseFloat(matrix[13])) ? 0 : parseFloat(matrix[13]) : isNaN(parseFloat(matrix[5])) ? 0 : parseFloat(matrix[5]);
  } else if (sty == "z") {
    return matrix.length > 6 ? parseFloat(matrix[14]) : 0;
  } else if (sty == "rotate") {
    return matrix.length > 6 ? this.getRotate([parseFloat(matrix[0]), parseFloat(matrix[1]), parseFloat(matrix[4]), parseFloat(matrix[5])]) : this.getRotate(matrix);
  }
}
SimpleDraw.prototype.getRotate = function (matrix) {
  var aa = Math.round(180 * Math.asin(matrix[0]) / Math.PI);
  var bb = Math.round(180 * Math.acos(matrix[1]) / Math.PI);
  var cc = Math.round(180 * Math.asin(matrix[2]) / Math.PI);
  var dd = Math.round(180 * Math.acos(matrix[3]) / Math.PI);
  var deg = 0;
  if (aa == bb || -aa == bb) {
    deg = dd;
  } else if (-aa + bb == 180) {
    deg = 180 + cc;
  } else if (aa + bb == 180) {
    deg = 360 - cc || 360 - dd;
  }
  return deg >= 360 ? 0 : deg;
}
SimpleDraw.prototype.deepClone = function (obj, deep) {
  var str = JSON.stringify(obj);
  return JSON.parse(str);
}
SimpleDraw.prototype.colorPick = function () {
  var util = {
    css: function (elem, obj) {
      for (var i in obj) {
        elem.style[i] = obj[i];
      }
    },
    hasClass: function (elem, classN) {
      var className = elem.getAttribute("class");
      return className.indexOf(classN) != -1;
    }
  };

  function Colorpicker(opt) {
    if (this === window) throw `Colorpicker: Can't call a function directly`;
    this.init(opt);
  };

  Colorpicker.prototype = {
    init(opt) {
      let {
        el,
        initColor = "rgb(255,0,0)",
        allMode = ['hex', 'rgb'],
        color = ''
      } = opt;

      this.Opt = {
        ...opt,
        el,
        initColor,
        allMode,
        color
      }

      this.elem_wrap = null; // 最外层容器
      this.fixedBg = null; // 拾色器后面固定定位的透明div 用于点击隐藏拾色器
      this.elem_colorPancel = null; // 色彩面板
      this.elem_picker = null; // 拾色器色块按钮
      this.elem_barPicker1 = null; // 颜色条
      this.elem_hexInput = null; // 显示hex的表单
      this.elem_showColor = null; // 显示当前颜色
      this.elem_showModeBtn = null; // 切换输入框模式按钮
      this.elem_inputWrap = null; // 输入框外层容器

      this.pancelLeft = 0;
      this.pancelTop = 0;

      this.downX = 0;
      this.downY = 0;
      this.moveX = 0;
      this.moveY = 0;

      this.pointLeft = 0;
      this.pointTop = 0;

      this.current_mode = 'hex'; // input框当前的模式

      this.rgba = {
        r: 0,
        g: 0,
        b: 0,
        a: 1
      };
      this.hsb = {
        h: 0,
        s: 100,
        b: 100
      };


      var _this = this,
          rgb = initColor.slice(4, -1).split(",");

      this.rgba.r = parseInt(rgb[0]);
      this.rgba.g = parseInt(rgb[1]);
      this.rgba.b = parseInt(rgb[2]);

      var body = document.getElementsByTagName("body")[0],
          div = document.createElement("div");

      div.innerHTML = this.render();
      body.appendChild(div);

      this.elem_wrap = div;
      this.fixedBg = div.children[0];
      this.elem_colorPancel = div.getElementsByClassName("color-pancel")[0];
      this.pancel_width = this.elem_colorPancel.offsetWidth;
      this.pancel_height = this.elem_colorPancel.offsetHeight;
      this.elem_picker = div.getElementsByClassName("pickerBtn")[0];
      this.elem_colorPalette = div.getElementsByClassName("color-palette")[0];
      this.elem_showColor = div.getElementsByClassName("colorpicker-showColor")[0];
      this.elem_barPicker1 = div.getElementsByClassName("colorBar-color-picker")[0];
      this.elem_hexInput = div.getElementsByClassName("colorpicker-hexInput")[0];
      this.elem_showModeBtn = div.getElementsByClassName("colorpicker-showModeBtn")[0];
      this.elem_inputWrap = div.getElementsByClassName("colorpicker-inputWrap")[0];


      util.css(div, {
        "position": "absolute",
        "z-index": 2,
        "display": 'none',
      });

      this.bindMove(this.elem_colorPancel, this.setPosition, true);
      this.bindMove(this.elem_barPicker1.parentNode, this.setBar, false);

      this.fixedBg.addEventListener("click", function (e) {
        _this.hide();
      }, false)

      this.elem_showModeBtn.addEventListener("click", function () {
        _this.switch_current_mode();
      }, false)

      this.elem_wrap.addEventListener("input", function (e) {
        var target = e.target,
            value = target.value;
        _this.setColorByInput(value);
      }, false);

      this.elem_colorPalette.addEventListener("click", function (e) {
        if (e.target.tagName.toLocaleLowerCase() == "p") {
          let colorStr = e.target.style.background;
          let rgb = colorStr.slice(4, -1).split(",");
          let rgba = {
            r: parseInt(rgb[0]),
            g: parseInt(rgb[1]),
            b: parseInt(rgb[2])
          }
          switch (_this.current_mode) {
            case "hex":
              _this.setColorByInput("#" + _this.rgbToHex(rgba))
              break;
            case 'rgb':
              let inputs = _this.elem_wrap.getElementsByTagName("input")
              inputs[0].value = rgba.r;
              inputs[1].value = rgba.g;
              inputs[2].value = rgba.b;
              _this.setColorByInput(colorStr)
              break;
          }

        }
      }, false);

      (color != '' && this.setColorByInput(color));
    },
    render: function () {
      var tpl =
          `<div style="position: fixed; top: 0px; right: 0px; bottom: 0px; left: 0px;"></div>
				<div style="position: inherit;z-index: 100;display: flex;box-shadow: rgba(0, 0, 0, 0.3) 0px 0px 2px, rgba(0, 0, 0, 0.3) 0px 4px 8px;">
					<div style='width:180px;padding:10px;background: #f9f9f9;display: flex;flex-flow: row wrap;align-content: space-around;justify-content: space-around;' class='color-palette'>
						${this.getPaletteColorsItem()}
					</div>
					<div class="colorpicker-pancel" style="background: rgb(255, 255, 255);box-sizing: initial; width: 225px; font-family: Menlo;">
						<div style="width: 100%; padding-bottom: 55%; position: relative; border-radius: 2px 2px 0px 0px; overflow: hidden;">
							<div class="color-pancel" style="position: absolute; top: 0px; right: 0px; bottom: 0px; left: 0px; background: rgb(${this.rgba.r},${this.rgba.g},${this.rgba.b})">
								<style>
									.saturation-white {background: -webkit-linear-gradient(to right, #fff, rgba(255,255,255,0));background: linear-gradient(to right, #fff, rgba(255,255,255,0));}
									.saturation-black {background: -webkit-linear-gradient(to top, #000, rgba(0,0,0,0));background: linear-gradient(to top, #000, rgba(0,0,0,0));}
								</style>
								<div class="saturation-white" style="position: absolute; top: 0px; right: 0px; bottom: 0px; left: 0px;">
									<div class="saturation-black" style="position: absolute; top: 0px; right: 0px; bottom: 0px; left: 0px;">
									</div>
									<div class="pickerBtn" style="position: absolute; top: 0%; left: 100%; cursor: default;">
										<div style="width: 12px; height: 12px; border-radius: 6px; box-shadow: rgb(255, 255, 255) 0px 0px 0px 1px inset; transform: translate(-6px, -6px);">
										</div>
									</div>
								</div>
							</div>
						</div>
						<div style="padding: 0 16px 20px;">
							<div class="flexbox-fix" style="display: flex;align-items: center;height: 40px;">
								<div style="width: 32px;">
									<div style="width: 16px; height: 16px; border-radius: 8px; position: relative; overflow: hidden;">
										<div class="colorpicker-showColor" style="position: absolute; top: 0px; right: 0px; bottom: 0px; left: 0px; border-radius: 8px; box-shadow: rgba(0, 0, 0, 0.1) 0px 0px 0px 1px inset; background:rgb(${this.rgba.r},${this.rgba.g},${this.rgba.b}); z-index: 2;"></div>
										<div class="" style="position: absolute; top: 0px; right: 0px; bottom: 0px; left: 0px; background: url(&quot;&quot;) left center;"></div>
									</div>
								</div>
								<div style="-webkit-box-flex: 1; flex: 1 1 0%;"><div style="height: 10px; position: relative;">
									<div style="position: absolute; top: 0px;right: 0px; bottom: 0px; left: 0px;">
										<div class="hue-horizontal" style="padding: 0px 2px; position: relative; height: 100%;">
											<style>
												.hue-horizontal {background: linear-gradient(to right, #f00 0%, #ff0 17%, #0f0 33%, #0ff 50%, #00f 67%, #f0f 83%, #f00 100%);background: -webkit-linear-gradient(to right, #f00 0%, #ff0 17%, #0f0 33%, #0ff 50%, #00f 67%, #f0f 83%, #f00 100%);}
												.hue-vertical {background: linear-gradient(to top, #f00 0%, #ff0 17%, #0f0 33%,#0ff 50%, #00f 67%, #f0f 83%, #f00 100%);background: -webkit-linear-gradient(to top, #f00 0%, #ff0 17%,#0f0 33%, #0ff 50%, #00f 67%, #f0f 83%, #f00 100%);}
											</style>
											<div  class="colorBar-color-picker" style="position: absolute; left: 0%;">
												<div style="width: 12px; height: 12px; border-radius: 6px; transform: translate(-6px, -1px); background-color: rgb(248, 248, 248); box-shadow: rgba(0, 0, 0, 0.37) 0px 1px 4px 0px;">
												</div>
											</div>
										</div>
									</div>
								</div>
							</div>
						</div>
						<div class="flexbox-fix" style="display: flex;">
							<div class="flexbox-fix colorpicker-inputWrap" style="-webkit-box-flex: 1; flex: 1 1 0%; display: flex; margin-left: -6px;">
									${this.getInputTpl()}
							</div>
							<div class="colorpicker-showModeBtn" style="width: 32px; text-align: right; position: relative;">
								<div style="margin-right: -4px;  cursor: pointer; position: relative;">
									<svg viewBox="0 0 24 24" style="width: 24px; height: 24px; border: 1px solid transparent; border-radius: 5px;"><path fill="#333" d="M12,5.83L15.17,9L16.58,7.59L12,3L7.41,7.59L8.83,9L12,5.83Z"></path><path fill="#333" d="M12,18.17L8.83,15L7.42,16.41L12,21L16.59,16.41L15.17,15Z"></path></svg>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div>`;
      return tpl;
    },
    getInputTpl: function () {
      var current_mode_html = "";
      switch (this.current_mode) {
        case 'hex':
          var hex = "#" + this.rgbToHex(this.HSBToRGB(this.hsb));
          current_mode_html += `
							<div style="padding-left: 6px; width: 100%;">
								<div style="position: relative;">
									<input class="colorpicker-hexInput" value="${hex}" spellcheck="false" style="font-size: 11px; color: rgb(51, 51, 51); width: 100%; border-radius: 2px; border: none; box-shadow: rgb(218, 218, 218) 0px 0px 0px 1px inset; height: 21px; text-align: center;">
									<span style="text-transform: uppercase; font-size: 11px; line-height: 11px; color: rgb(150, 150, 150); text-align: center; display: block; margin-top: 12px;">hex</span>
								</div>
							</div>`;
          break;
        case 'rgb':
          for (var i = 0; i < 3; i++) {
            current_mode_html +=
                `<div style="padding-left: 6px; width: 100%;">
								<div style="position: relative;">
									<input class="colorpicker-hexInput" value="${this.rgba['rgb'[i]]}" spellcheck="false" style="font-size: 11px; color: rgb(51, 51, 51); width: 100%; border-radius: 2px; border: none; box-shadow: rgb(218, 218, 218) 0px 0px 0px 1px inset; height: 21px; text-align: center;">
									<span style="text-transform: uppercase; font-size: 11px; line-height: 11px; color: rgb(150, 150, 150); text-align: center; display: block; margin-top: 12px;">${'rgb'[i]}</span>
								</div>
							</div>`;
          }
        default:
      }
      return current_mode_html;
    },
    getPaletteColorsItem: function () {
      let str = '';
      let palette = ["rgb(0, 0, 0)", "rgb(67, 67, 67)", "rgb(102, 102, 102)", "rgb(204, 204, 204)", "rgb(217, 217, 217)", "rgb(255, 255, 255)",
        "rgb(152, 0, 0)", "rgb(255, 0, 0)", "rgb(255, 153, 0)", "rgb(255, 255, 0)", "rgb(0, 255, 0)", "rgb(0, 255, 255)",
        "rgb(74, 134, 232)", "rgb(0, 0, 255)", "rgb(153, 0, 255)", "rgb(255, 0, 255)", "rgb(230, 184, 175)", "rgb(244, 204, 204)",
        "rgb(252, 229, 205)", "rgb(255, 242, 204)", "rgb(217, 234, 211)", "rgb(208, 224, 227)", "rgb(201, 218, 248)", "rgb(207, 226, 243)",
        "rgb(217, 210, 233)", "rgb(234, 209, 220)", "rgb(221, 126, 107)", "rgb(234, 153, 153)", "rgb(249, 203, 156)", "rgb(255, 229, 153)",
        "rgb(182, 215, 168)", "rgb(162, 196, 201)", "rgb(164, 194, 244)", "rgb(159, 197, 232)", "rgb(180, 167, 214)"
      ]
      palette.forEach(item => str += `<p style='width:20px;height:20px;background:${item};margin:0 5px;border: solid 1px #d0d0d0;'></p>`)
      return str;
    },
    setPosition(x, y) {
      var LEFT = parseInt(x - this.pancelLeft),
          TOP = parseInt(y - this.pancelTop);

      this.pointLeft = Math.max(0, Math.min(LEFT, this.pancel_width));
      this.pointTop = Math.max(0, Math.min(TOP, this.pancel_height));

      util.css(this.elem_picker, {
        left: this.pointLeft + "px",
        top: this.pointTop + "px"
      })
      this.hsb.s = parseInt(100 * this.pointLeft / this.pancel_width);
      this.hsb.b = parseInt(100 * (this.pancel_height - this.pointTop) / this.pancel_height);

      this.setShowColor();
      this.setValue(this.rgba);

    },
    setBar: function (elem, x) {
      var elem_bar = elem.getElementsByTagName("div")[0],
          rect = elem.getBoundingClientRect(),
          elem_width = elem.offsetWidth,
          X = Math.max(0, Math.min(x - rect.x, elem_width));

      if (elem_bar === this.elem_barPicker1) {
        util.css(elem_bar, {
          left: X + "px"
        });
        this.hsb.h = parseInt(360 * X / elem_width);
      } else {
        util.css(elem_bar, {
          left: X + "px"
        });
        this.rgba.a = X / elem_width;
      }

      this.setPancelColor(this.hsb.h);
      this.setShowColor();
      this.setValue(this.rgba);

    },
    setPancelColor: function (h) {
      var rgb = this.HSBToRGB({
        h: h,
        s: 100,
        b: 100
      });

      util.css(this.elem_colorPancel, {
        background: 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' + this.rgba.a + ')'
      });
    },
    setShowColor: function () {
      var rgb = this.HSBToRGB(this.hsb);

      this.rgba.r = rgb.r;
      this.rgba.g = rgb.g;
      this.rgba.b = rgb.b;

      util.css(this.elem_showColor, {
        background: 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' + this.rgba.a + ')'
      });
    },
    setValue: function (rgb) {
      var hex = "#" + this.rgbToHex(rgb);
      this.elem_inputWrap.innerHTML = this.getInputTpl();
      this.Opt.change(hex, this.ele_id, this.ele_type);
    },
    setColorByInput: function (value) {
      var _this = this;
      switch (this.current_mode) {
        case "hex":
          value = value.slice(1);
          if (value.length == 3) {
            value = '#' + value[0] + value[0] + value[1] + value[1] + value[2] + value[2];
            this.hsb = this.hexToHsb(value);
          } else if (value.length == 6) {
            this.hsb = this.hexToHsb(value);
          }
          break;
        case 'rgb':
          var inputs = this.elem_wrap.getElementsByTagName("input"),
              rgb = {
                r: inputs[0].value ? parseInt(inputs[0].value) : 0,
                g: inputs[1].value ? parseInt(inputs[1].value) : 0,
                b: inputs[2].value ? parseInt(inputs[2].value) : 0
              };

          this.hsb = this.rgbToHsb(rgb);
      }
      this.changeViewByHsb();
    },
    changeViewByHsb: function () {
      this.pointLeft = parseInt(this.hsb.s * this.pancel_width / 100);
      this.pointTop = parseInt((100 - this.hsb.b) * this.pancel_height / 100);
      util.css(this.elem_picker, {
        left: this.pointLeft + "px",
        top: this.pointTop + "px"
      });

      this.setPancelColor(this.hsb.h);
      this.setShowColor();
      util.css(this.elem_barPicker1, {
        left: this.hsb.h / 360 * (this.elem_barPicker1.parentNode.offsetWidth) + "px"
      });

      var hex = '#' + this.rgbToHex(this.HSBToRGB(this.hsb));
      this.Opt.change(hex, this.ele_id, this.ele_type);
    },
    switch_current_mode: function () {
      this.current_mode = this.current_mode == 'hex' ? 'rgb' : 'hex';
      this.elem_inputWrap.innerHTML = this.getInputTpl();
    },
    bindMove: function (elem, fn, bool) {
      var _this = this;

      elem.addEventListener("mousedown", function (e) {
        _this.downX = e.pageX;
        _this.downY = e.pageY;
        bool ? fn.call(_this, _this.downX, _this.downY) : fn.call(_this, elem, _this.downX, _this.downY);

        document.addEventListener("mousemove", mousemove, false);

        function mousemove(e) {
          _this.moveX = e.pageX;
          _this.moveY = e.pageY;
          bool ? fn.call(_this, _this.moveX, _this.moveY) : fn.call(_this, elem, _this.moveX, _this.moveY);
          e.preventDefault();
        }
        document.addEventListener("mouseup", mouseup, false);

        function mouseup(e) {
          document.removeEventListener("mousemove", mousemove, false)
          document.removeEventListener("mouseup", mouseup, false)
        }
      }, false);
    },
    show: function (x, y, id, type) {
      this.pancelLeft = x;
      this.pancelTop = y;
      this.ele_id = id;
      this.ele_type = type;
      util.css(this.elem_wrap, {
        "display": "block",
        "left": x + "px",
        "top": y + "px"
      })
    },
    hide: function () {
      util.css(this.elem_wrap, {
        "display": "none"
      })
    },
    HSBToRGB: function (hsb) {
      var rgb = {};
      var h = Math.round(hsb.h);
      var s = Math.round(hsb.s * 255 / 100);
      var v = Math.round(hsb.b * 255 / 100);

      if (s == 0) {
        rgb.r = rgb.g = rgb.b = v;
      } else {
        var t1 = v;
        var t2 = (255 - s) * v / 255;
        var t3 = (t1 - t2) * (h % 60) / 60;

        if (h == 360) h = 0;

        if (h < 60) {
          rgb.r = t1;
          rgb.b = t2;
          rgb.g = t2 + t3
        } else if (h < 120) {
          rgb.g = t1;
          rgb.b = t2;
          rgb.r = t1 - t3
        } else if (h < 180) {
          rgb.g = t1;
          rgb.r = t2;
          rgb.b = t2 + t3
        } else if (h < 240) {
          rgb.b = t1;
          rgb.r = t2;
          rgb.g = t1 - t3
        } else if (h < 300) {
          rgb.b = t1;
          rgb.g = t2;
          rgb.r = t2 + t3
        } else if (h < 360) {
          rgb.r = t1;
          rgb.g = t2;
          rgb.b = t1 - t3
        } else {
          rgb.r = 0;
          rgb.g = 0;
          rgb.b = 0
        }
      }

      return {
        r: Math.round(rgb.r),
        g: Math.round(rgb.g),
        b: Math.round(rgb.b)
      };
    },
    rgbToHex: function (rgb) {
      var hex = [
        rgb.r.toString(16),
        rgb.g.toString(16),
        rgb.b.toString(16)
      ];
      hex.map(function (str, i) {
        if (str.length == 1) {
          hex[i] = '0' + str;
        }
      });

      return hex.join('');
    },
    hexToRgb: function (hex) {
      var hex = parseInt(((hex.indexOf('#') > -1) ? hex.substring(1) : hex), 16);
      return {
        r: hex >> 16,
        g: (hex & 0x00FF00) >> 8,
        b: (hex & 0x0000FF)
      };
    },
    hexToHsb: function (hex) {
      return this.rgbToHsb(this.hexToRgb(hex));
    },
    rgbToHsb: function (rgb) {
      var hsb = {
        h: 0,
        s: 0,
        b: 0
      };
      var min = Math.min(rgb.r, rgb.g, rgb.b);
      var max = Math.max(rgb.r, rgb.g, rgb.b);
      var delta = max - min;
      hsb.b = max;
      hsb.s = max != 0 ? 255 * delta / max : 0;
      if (hsb.s != 0) {
        if (rgb.r == max) hsb.h = (rgb.g - rgb.b) / delta;
        else if (rgb.g == max) hsb.h = 2 + (rgb.b - rgb.r) / delta;
        else hsb.h = 4 + (rgb.r - rgb.g) / delta;
      } else hsb.h = -1;
      hsb.h *= 60;
      if (hsb.h < 0) hsb.h += 360;
      hsb.s *= 100 / 255;
      hsb.b *= 100 / 255;
      return hsb;
    }
  }

  Colorpicker.create = function (opt) {
    return new Colorpicker(opt)
  }

  this.colorPicker = Colorpicker.create({
    color: "#000fff",
    change: (color, id, type) => {
      switch (type) {
        case 'line':
          this.changeLineColor(id, color);
          break;
        case 'core':
          this.changeCoreColor(id, color);
          break;
        case 'label':
          this.changeLabelColor(id, color);
          break;
      }
    }
  });
}
export default SimpleDraw;
